package com.tongtech.space.controller.login;

import com.alibaba.fastjson.JSON;
import com.dsjzx.sm4.crypto.impl.SM4Util;
import com.tongtech.space.common.constants.Constants;
import com.tongtech.space.common.enums.UserTypeEnums;
import com.tongtech.space.common.pojo.Result;
import com.tongtech.space.common.pojo.UserInfo;
import com.tongtech.space.module.login.model.LoginDto;
import com.tongtech.space.module.login.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import static com.tongtech.space.common.constants.Constants.SESSION_USER_INFO;

/**
 * 登录
 *
 * @author jinjiayu
 * @since 2020/12/16
 */
@Slf4j
@RestController
@RequestMapping(Constants.URL_API_VERSION + "/login")
@Api(tags = "登录相关")
public class LoginController {

    @Value("${login.personErrorUrl}")
    private String personErrorUrl;
    @Value("${login.legalErrorUrl}")
    private String legalErrorUrl;

    @Autowired
    private LoginService loginService;

    /**
     * 移动端登录
     * 1.调用统一身份认证接口获取 个人 用户信息
     * 2.将用户信息转换为UserInfo对象
     * 3.创建session会话,将UserInfo对象绑定到session中
     * 4.跳转到空间首页
     *
     * @param loginDto
     * @param request response
     * @author jinjiayu
     */
    @ApiOperation(value = "登录")
    @GetMapping("/in")
    public void in(@Validated LoginDto loginDto,
                   HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 1.调用统一身份认证接口获取 个人/法人 用户信息, 并将用户信息转换为UserInfo对象
        UserInfo userInfo = loginService.getUserInfo(loginDto);
        if (userInfo == null) {
            // 跳转到错误地址或者首页
            response.sendRedirect(loginDto.getUserType() == UserTypeEnums.NATURE_PERSON.getCode() ? personErrorUrl : legalErrorUrl);
            return;
        }

        // 2.创建session会话,将UserInfo对象绑定到session中
        HttpSession session = request.getSession();
        session.setAttribute(SESSION_USER_INFO, userInfo);

        // 3.Todo 跳转页面
        String redirectUrl;
        if (loginDto.getUserType() == UserTypeEnums.NATURE_PERSON.getCode()) {
            redirectUrl = personErrorUrl;
        } else {
            redirectUrl = legalErrorUrl;
        }
        response.sendRedirect(redirectUrl);
    }

    /**
     * 登出
     *
     * @param request response
     * @author jinjiayu
     */
    @ApiOperation(value = "登出")
    @GetMapping("/out")
    public void loginOut(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session=request.getSession(false);
        if (session == null) {
            return;
        }

        // 1.删除session中所有的参数
        Enumeration<String> attributeNames = session.getAttributeNames();
        while(attributeNames.hasMoreElements()){
            request.getSession().removeAttribute(attributeNames.nextElement());
        }

        // 2.清除session
        request.getSession().invalidate();

        // 3.Todo 清除相应用户数据的缓存等


    }

    /**
     * 返回错误信息
     *
     * @param response errorStr
     * @author jinjiayu
     */
    private void returnErrorStr(HttpServletResponse response, String errorStr, int httpCode) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(httpCode);
            PrintWriter writer = response.getWriter();
            Result<?> fail = Result.fail(errorStr);
            writer.print(JSON.toJSONString(fail));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
